<template>
    <el-collapse v-model="activeNames" v-show="customTemplate.guid!=select">
        <!-- 数据源绑定 -->
        <el-collapse-item title="数据源绑定" name="api">
            <div class="apiBox">
                <template v-if="component?.api">
                    <VueDraggable v-model="component.api" @end="tipDisabled=false">
                        <el-tooltip v-for="item in component.api" placement="left" effect="light" :hide-after="80"
                        :show-arrow="false" :offset="1" popper-style="padding:3px;" :disabled="tipDisabled">
                            <template #content>
                                <el-button type="danger" plain :icon="Delete" @click="actionAPI(item,true)"/>
                            </template>
                            <el-button round plain @click="actionAPI(item)" @mousedown="tipDisabled=true">
                                {{ getAPITitle(item) }}
                            </el-button>
                        </el-tooltip>
                    </VueDraggable>
                </template>
                <el-button type="primary" round plain @click="actionAPI()">新增数据源</el-button>
            </div>
        </el-collapse-item>
        <!-- 初始数据 -->
        <el-collapse-item title="初始数据" name="defaultData">
            <el-input disabled type="textarea" :rows="10" v-model="defaultData"></el-input>
        </el-collapse-item>
        <!-- 渲染数据 -->
        <el-collapse-item title="渲染数据" name="data">
            <el-input type="textarea" :rows="20" v-model="renderDate"></el-input>
        </el-collapse-item>
    </el-collapse>
    <el-form label-width="auto" size="small" label-position="top">
        <el-collapse v-model="activeNames" v-if="customTemplate.guid==select">
            <template v-for="collapse in customTemplate.template" :key="collapse.guid">
                <!-- 数据源绑定 -->
                <el-collapse-item v-if="collapse.name=='systemApi'&&collapse.label=='数据源绑定'"
                 title="数据源绑定" name="api">
                    <div class="apiBox">
                        <template v-if="component?.api">
                            <VueDraggable v-model="component.api" @end="tipDisabled=false">
                                <el-tooltip v-for="item in component.api" placement="left" effect="light" :hide-after="80"
                                :show-arrow="false" :offset="1" popper-style="padding:3px;" :disabled="tipDisabled">
                                    <template #content>
                                        <el-button type="danger" plain :icon="Delete" @click="actionAPI(item,true)"/>
                                    </template>
                                    <el-button round plain @click="actionAPI(item)" @mousedown="tipDisabled=true">
                                        {{ getAPITitle(item) }}
                                    </el-button>
                                </el-tooltip>
                            </VueDraggable>
                        </template>
                        <el-button type="primary" round plain @click="actionAPI()">新增数据源</el-button>
                        <template v-if="'template' in collapse&&'config' in collapse">
                            <template v-for="form in collapse.template">
                                <customComp :attrs="form" :config="collapse.config"/>
                            </template>
                        </template>
                    </div>
                </el-collapse-item>
                <!-- 初始数据 -->
                <el-collapse-item v-else-if="collapse.name=='systemDefaultData'&&collapse.label=='初始数据'"
                 title="初始数据" name="defaultData">
                    <el-input disabled type="textarea" :rows="10" v-model="defaultData"></el-input>
                </el-collapse-item>
                <!-- 渲染数据 -->
                <el-collapse-item v-else-if="collapse.name=='systemData'&&collapse.label=='渲染数据'"
                 title="渲染数据" name="data">
                    <el-input type="textarea" :rows="20" v-model="renderDate"></el-input>
                </el-collapse-item>
                <el-collapse-item v-else-if="'template' in collapse&&'config' in collapse" :title="collapse.label" :name="collapse.name">
                    <template v-for="form in collapse.template">
                        <customComp :attrs="form" :config="collapse.config"/>
                    </template>
                </el-collapse-item>
            </template>
        </el-collapse>
    </el-form>
</template>
<script setup lang="tsx">
import {computed,inject,ref,watch} from 'vue'
import {select,data} from '@drag/store'
import {find} from '@drag/utils'
import customComp from './customComp.vue'
import {showMsg} from '@dashboard/utils'
import {ElMessage,ElMessageBox} from 'element-plus'
import {Delete} from '@element-plus/icons-vue'
import type {CustomTemplate} from '@dashboard/render/src/types'

// 自定义模板数据
const customTemplate = ref<CustomTemplate>({guid:'',template:[]})
window.customTemplate = customTemplate;
/**关闭页面数据源弹窗 */
let closeMessage:Function;
const eventBus = inject<any>('eventBus');
const tipDisabled = ref(false)
/**当前是否有组件选中 */
const isSel = computed(()=>{
    return typeof select.value === 'number'||typeof select.value=== 'string'
})
/**当前选中组件数据 */
const component = computed(()=>{
    if(typeof select.value === 'number'||typeof select.value=== 'string'){
        return find({nodeId:select.value,tree:data.value,meNode:true})
    }
    return {} as {[key:string]:any};
})
const defaultData = computed(()=>{
    let item = component.value?.defaultData
    return typeof item == 'object'?JSON.stringify(item,null,2):'';
})
const renderDate = computed({
    get(){
        let item = component.value?.data
        return typeof item == 'object'?JSON.stringify(item,null,2):'';
    },
    set: (val) => {
        if(isSel.value){
            try {
                let parse = JSON.parse(val)
                component.value.data = parse
            } catch (error) {
                component.value.data = val
            }
        }
    }
})
const activeNames = ref<string[]>([])
let oldTemplate:string[] = [];
//缓存相同模板展开的状态
watch(select,cacheCollapse)
/**
 * 更新API
 * @param api 要被设置的API数据，如果不传代表新增API
 * @param del 是否删除当前API
 */
const actionAPI = (api:{[key:string]:any}={guid:Date.now()},del=false)=>{
    if(del){
        ElMessageBox.confirm(`是否删除数据源【${getAPITitle(api)}】`,'Warning',{
            confirmButtonText: '是的',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(()=>{
            component.value.api.splice(component.value.api.findIndex(e=>e.guid==api.guid),1)
            ElMessage({message: '删除成功！',type: 'success'})
        }).catch(()=>{})
    }
    else if(isSel.value){
        api.alias??=api.guid;
        closeMessage = showMsg({
            title:'数据源配置',
            url:'/Html/Custom/AutoPage/index.html?Dev_PageConfigOID=ed40f94c-7e44-4e15-b66d-dde4d7f0b62a'+(api.tag?'':'&w=1'),
            success(iframe){
                let win = iframe.contentWindow!;
                win.dashboard = api;
                win.api = component.value.api||[];
                win.getAPITitle = getAPITitle;
            }
        })
    }
    else{
        ElMessage({
            message: '请选中组件再新增数据源！',
            type: 'warning',
        })
    }
}
/**根据数据源获取标题
 * @param api 数据源对象
 */
function getAPITitle(api:{[key:string]:any}){
    return api.Title+`（${(api.Relation?(api.Relation=='1'?'子':'参与者'):'主')}）`
}
/**缓存相同模板展开的状态*/
function cacheCollapse(){
    if(customTemplate.value.guid == select.value){
        let active = customTemplate.value.template.map(e=>e.name);
        if(JSON.stringify(oldTemplate)!=JSON.stringify(active)){
            activeNames.value = active;
            oldTemplate = active;
        }
    }
    else{
        activeNames.value = ['api'];
        oldTemplate = ['api'];
    }
}
//监听模板更新事件
eventBus.on('updTemplate',data=>{
    customTemplate.value = data
    cacheCollapse()
})
//监听页面数据源更新事件
window.addEventListener('message', ({data}) => {
    if(data.type=='DataAPI'&&isSel.value){
        let value = data.data;
        if(!component.value.api)component.value.api = [];
        let i = component.value.api.findIndex(e=>e.guid==value.guid)
        if(i==-1)component.value.api.push(value);
        else component.value.api[i] = value;
        if(data.close)closeMessage()
        ElMessage({message: '保存成功！',type: 'success'})
    }
})
</script>
<style scoped>
.el-form-item>:deep(label){
    margin:0;
}
.apiBox .el-button{
    width: 100%;margin:0;margin-bottom:10px;
}
:deep(.el-collapse-item__content){
    padding: 10px;
}
:deep(.el-collapse-item__header){
    padding-left: 10px;
}
</style>